<template>
  <div>
    <el-select
      v-model="selDvyId"
      v-loadmore="loadmore"
      :style="selStyle"
      filterable
      remote
      :remote-method="remoteMethod"
      :placeholder="placeTips"
      :disabled="disabled"
      @change="change"
      @keyup.enter.stop="none"
    >
      <el-option
        v-for="item in devList"
        :key="item.dvyId"
        :label="item.dvyName"
        :value="item.dvyId"
      />
    </el-select>
  </div>
</template>

<script setup>
import { watch } from 'vue'
const emit = defineEmits(['update:modelValue'])
const selDvyId = ref('') // 当前选择的值
const size = ref(20)
const current = ref(1)
const dvyName = ref('')
const pages = ref(0)
const devList = ref([])
const isSearch = ref(false)
const vLoadmore = {
  mounted: (el, binding) => {
    const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
    SELECTWRAP_DOM?.addEventListener('scroll', function () {
      const condition =
        document.documentElement.scrollHeight - document.documentElement.scrollTop <=
        document.documentElement.clientHeight
      if (condition) {
        binding.value()
      }
    })
  }
}

const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: ''
  },
  selStyle: {
    type: Object,
    default: () => {}
  },
  placeTips: {
    type: String,
    default: '请选择'
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

watch(
  () => props.modelValue,
  val => {
    selDvyId.value = val
  },
  { immediate: true }
)

onMounted(() => {
  getDeliveryList()
})

const change = () => {
  emit('update:modelValue', selDvyId.value)
}
const remoteMethod = name => {
  isSearch.value = true
  current.value = 1
  dvyName.value = name
  getDeliveryList()
}
// 获取物流列表
const getDeliveryList = () => {
  http({
    url: http.adornUrl('/admin/delivery/page'),
    method: 'get',
    params: http.adornParams({
      size: size.value,
      current: current.value,
      dvyName: dvyName.value
    })
  }).then(({ data }) => {
    current.value = data.current
    pages.value = data.pages
    if (data.current === 1) {
      devList.value = data.records
      if (selDvyId.value && !isSearch.value) {
        checkCurSel(devList.value, selDvyId.value)
      }
    } else {
      const fList = data.records.filter(r => r.dvyId !== selDvyId.value)
      devList.value.push(...fList)
    }
  })
}
// 获取当前id的物流
const getDeliveryById = dvyId => {
  http({
    url: http.adornUrl('/admin/delivery/page'),
    method: 'get',
    params: http.adornParams({
      dvyId
    })
  }).then(({ data }) => {
    devList.value.unshift(...data.records)
  })
}
// 分页加载
const loadmore = () => {
  if (current.value < pages.value) {
    current.value++
    getDeliveryList()
  }
}
// 筛查出当前所选的对象
const checkCurSel = (curList, curId) => {
  for (const item of curList) {
    if (item.dvyId === curId) {
      return
    }
  }
  getDeliveryById(curId)
}
</script>
